package com.base.core.error;

import com.base.core.type.JsonUtils;
import com.base.core.util.StringUtils;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.databind.node.ObjectNode;


@SuppressWarnings("serial")
public class GenericException extends RuntimeException {
    
    private EnumWithText error;

    public GenericException(EnumWithText error) {
        super();
        this.error = error;
    }

    public GenericException(EnumWithText error, String message) {
        super(message);
        this.error = error;
    }

    public GenericException(EnumWithText error, Throwable cause) {
        super(cause);
        this.error = error;
    }
    
    public GenericException(EnumWithText error, String message, Throwable cause) {
        super(message, cause);
        this.error = error;
    }

    @JsonValue
    public ObjectNode getJsonValue() {
        ObjectNode on = JsonUtils.mapper().createObjectNode();
        on.put("code", error.toString());
        on.put("text", error.text());
        on.put("message", toString());
        return on;
    }

    public EnumWithText getError() {
        return error;
    }

    @Override
    public String toString() {
        Object m = StringUtils.firstNotNull(getMessage(), error.text());
        return m == null ? getCause().toString() : m.toString();
    }
}
